package com.yuerlive.rainbow.module.live.fragment;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.BottomSheetDialog;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.protobuf.InvalidProtocolBufferException;
import com.mrd.game.message.HOpCodeEx;
import com.mrd.game.message.RainbowMessage;
import com.mrd.mina.MinaCallback;
import com.mrd.mina.MinaHelper;
import com.mrd.packet.Packet;
import com.netease.nimlib.sdk.chatroom.ChatRoomMessageBuilder;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMember;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomMessage;
import com.netease.nimlib.sdk.chatroom.model.ChatRoomNotificationAttachment;
import com.netease.nimlib.sdk.msg.constant.NotificationType;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yuerlive.rainbow.R;
import com.yuerlive.rainbow.base.BaseActivity;
import com.yuerlive.rainbow.base.BaseFragment;
import com.yuerlive.rainbow.common.BaseRecycleViewAdapter;
import com.yuerlive.rainbow.entity.AllPlatformData;
import com.yuerlive.rainbow.entity.BaseData;
import com.yuerlive.rainbow.entity.DayTaskData;
import com.yuerlive.rainbow.entity.GameInfo;
import com.yuerlive.rainbow.entity.Gift;
import com.yuerlive.rainbow.entity.LiveDetailData;
import com.yuerlive.rainbow.entity.MissionData;
import com.yuerlive.rainbow.entity.ShareData;
import com.yuerlive.rainbow.entity.ShareInfo;
import com.yuerlive.rainbow.entity.SpecialGift;
import com.yuerlive.rainbow.entity.User;
import com.yuerlive.rainbow.entity.UserInfo;
import com.yuerlive.rainbow.module.homepage.HomePageActivity;
import com.yuerlive.rainbow.module.live.ContributionsActivity;
import com.yuerlive.rainbow.module.live.LiveFinishActivity;
import com.yuerlive.rainbow.module.live.LiveRoomActivity;
import com.yuerlive.rainbow.module.live.adapter.ChatItemAdapter;
import com.yuerlive.rainbow.module.live.adapter.MemberAdapter;
import com.yuerlive.rainbow.module.live.adapter.TaskAdatpter;
import com.yuerlive.rainbow.module.live.presenter.ChatRoomContract;
import com.yuerlive.rainbow.module.live.presenter.ChatRoomPresenter;
import com.yuerlive.rainbow.module.playlive.LiveEndActivity;
import com.yuerlive.rainbow.module.playlive.PlayLiveRoomActivity;
import com.yuerlive.rainbow.module.playlive.adapter.GameListAdapter;
import com.yuerlive.rainbow.nim.ChatRoomMemberListener;
import com.yuerlive.rainbow.nim.CustomMessage;
import com.yuerlive.rainbow.nim.EnterChatRoomCallback;
import com.yuerlive.rainbow.nim.GiftAttachment;
import com.yuerlive.rainbow.nim.NimHelper;
import com.yuerlive.rainbow.nim.OnMessageReceiveListener;
import com.yuerlive.rainbow.nim.SendMsgCallback;
import com.yuerlive.rainbow.observer.Observerable;
import com.yuerlive.rainbow.observer.ObserverableType;
import com.yuerlive.rainbow.utils.DeviceUtils;
import com.yuerlive.rainbow.utils.FormatUtil;
import com.yuerlive.rainbow.utils.GlideUtil;
import com.yuerlive.rainbow.utils.L;
import com.yuerlive.rainbow.utils.MyAnimationDrawable;
import com.yuerlive.rainbow.utils.PreferenceUtils;
import com.yuerlive.rainbow.utils.ShareUtils;
import com.yuerlive.rainbow.utils.UserProxy;
import com.yuerlive.rainbow.utils.Utils;
import com.yuerlive.rainbow.widget.ButtomDialog;
import com.yuerlive.rainbow.widget.CircleImageView;
import com.yuerlive.rainbow.widget.CustomBottomSheetDialog;
import com.yuerlive.rainbow.widget.CustomDialog;
import com.yuerlive.rainbow.widget.GiftShowLayout;
import com.yuerlive.rainbow.widget.GiftView;
import com.yuerlive.rainbow.widget.HorizontalListView;
import com.yuerlive.rainbow.widget.InputDialog;
import com.yuerlive.rainbow.widget.InputEdittext;
import com.yuerlive.rainbow.widget.PiaoPingView;
import com.yuerlive.rainbow.widget.ShareDialog;
import com.yuerlive.rainbow.widget.timeselector.TextUtil;

import org.apache.mina.core.session.IoSession;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingDeque;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.OnClick;

import static com.yuerlive.rainbow.observer.ObserverableType.EXITLIVEROOM;
import static com.yuerlive.rainbow.observer.ObserverableType.GETBANKERINFO;
import static com.yuerlive.rainbow.observer.ObserverableType.ISBANKER;

/**
 * Created by xiaoyi on 2017/5/23.
 */

public class FragmentChatRoom extends BaseFragment implements OnMessageReceiveListener, ChatItemAdapter.CommentOnClickListener, View.OnTouchListener
        , GiftView.SendGiftListener, MinaCallback, ChatRoomMemberListener, ChatRoomContract.View, GiftView.GiftAnimationListener, UserProxy.OnUserChangeListener,
        TaskAdatpter.GetListener, Observerable.ISubscribe {
    @BindView(R.id.rlParent)
    RelativeLayout rlParent;
    @BindView(R.id.tvNickName)
    TextView tvNickName;

    @BindView(R.id.llChat)
    View llChat;

    @BindView(R.id.rlAction)
    View rlAction;

    @BindView(R.id.ivHelp)
    ImageView ivHelp;

    @BindView(R.id.imgChat)
    ImageView imgChat;
    @BindView(R.id.imgGift)
    ImageView imgGift;

    @BindView(R.id.ivGame)
    ImageView ivGame;
    @BindView(R.id.ivCamera)
    ImageView ivCamera;

    @BindView(R.id.ivMeiyan)
    ImageView imgMeiyan;

    @BindView(R.id.lvAudience)
    HorizontalListView lvAudience;
    @BindView(R.id.ivExit)
    ImageView ivExit;
    @BindView(R.id.llAnchorInfo)
    LinearLayout llAnchorInfo;
    @BindView(R.id.lvmessage)
    ListView lvmessage;
    @BindView(R.id.llgiftcontent)
    GiftShowLayout llgiftcontent;

    @BindView(R.id.tvID)
    TextView tvID;
    @BindView(R.id.tvRank)
    TextView tvRank;
    @BindView(R.id.imgAnchorHeader)
    ImageView imgHeader;

    InputEdittext editChat;

    @BindView(R.id.tvFollow)
    TextView tvFollow;

    HorizontalListView lvGame;
    GameListAdapter gameListAdapter;
    List<GameInfo> gameList = new ArrayList<>();

    private boolean isBanker;

    @BindView(R.id.giftView)
    GiftView giftView;
    //    @BindView(R.id.piaoPingView)
//    PiaoPingView piaoPingView;
    @BindView(R.id.ivShare)
    ImageView ivShare;
    @BindView(R.id.llRewards)
    LinearLayout llRewards;
    @BindView(R.id.llTask)
    LinearLayout llTask;
    ChatItemAdapter chatItemAdapter;
    List<Object> chatMessages = new ArrayList<>();
    long lastSendTime;
    private Gift mOldGift;
    private int mBatter = 1;
    ChatRoomMessage mChatRoomMessage;
    private boolean bSendGiftMessage = false;
    MemberAdapter memberAdapter;
    private ShareDialog shareDialog;
    private int gameID;
    private int liveID;

    List<ChatRoomMember> chatRoomMembers = new ArrayList<>();
    // private List<PiaoPingView> piaoPingViews = new ArrayList<>();
    private Map<Integer, PiaoPingView> piaoPingViews = new HashMap<>();

    @BindString(R.string.introduce_catmouse)
    String introduceCatMouse;
    @BindString(R.string.introduce_play_catmouse)
    String introducePlayCatmouse;
    @BindString(R.string.introduce_niuniu)
    String introduceNiuniu;
    @BindString(R.string.introduce_play_niuniu)
    String introducePlayNiuniu;

    @BindString(R.string.introduce_sanguo)
    String introduceSanguo;
    @BindString(R.string.introduce_play_sanguo)
    String introducePlaySanguo;

    @BindString(R.string.hint_closegame)
    String hintCloseGame;

    private boolean closeGame;

    private boolean hasGame;

    CustomDialog userCard;
    View cardView;
    //用户卡片
    TextView tvCardNickName;
    TextView tvLevel;
    TextView tvCardId;
    TextView tvWords;
    TextView tvFollowCount;
    TextView tvCardFollow;
    TextView tvFansCount;
    TextView tvCardCharmCount;
    LinearLayout llCount;
    CircleImageView imgCardHeader;
    TextView tvReport;
    TextView tvHomePage;
    View spliteLine;

    ChatRoomContract.Presenter presenter;
    private LiveDetailData liveDetail;

    FragmentLayer parentFragment;

    Thread minaThread;
    private ChatHandler mHandler;
    private static final int CODE_SENDGIFT = 0X2001;
    private static final int CODE_DAILY = 0X5001; //日常福利倒计时
    private static final int CODE_BIG_GIFT = 0X6001; //大额礼物
    private static final int CODE_CLOSE_VIDEO = 0X6002; //关闭视频
    private static final int CODE_CLOSE_ALL = 0X6003; //关闭直播间
    private static final int CODE_CLOSE_GAME = 0X6004; //关闭游戏

    private static final int CODE_CHANGE_GAME = 0X7001;  //切换游戏
    private static final int CODE_LOAD_GAME = 0X7002;  //加载游戏（只有一种情况下出现：没有游戏的直播间载入了游戏）

    /*手指监听*/
    private int startY;
    private int endY;

    private CustomDialog assictanceDialog; // 游戏帮助
    private ShareInfo shareInfo;

    private CustomDialog introduceGameDialog; // 游戏介绍(切换游戏)
    private TextView tvGameIntroduce;
    private TextView tvGameIntroducePlay;

    private CustomDialog closeGameDialog;  //关闭游戏提醒对话框

    private String chatRoomID;
    private UserInfo info;

    CustomDialog dailyDialog;
    TextView tvCount;
    TextView tvTimes;

    public static final int NOTICE_PIAO_PING_VIEW = 4;
    public static final int SPECIAL_PIAO_PING_VIEW = 3;
    public static final int COMMON_PIAO_PING_VIEW = 1;
    public static final int DOUBLE_HIT_GIFT = 2;
    public static final int MEMBER_IN = 5;

    public static final String BIG_GIT_NAME_1 = "房产证";
    public static final String BIG_GIT_NAME_2 = "女神";
    public static final String BIG_GIT_NAME_3 = "求婚";

    /*日常福利*/
    @BindView(R.id.llDaily)
    LinearLayout llDaily;
    @BindView(R.id.tvDailyTime)
    TextView tvDailyTime;
    @BindView(R.id.tvDailyCount)
    TextView tvDailyCount;

    @BindView(R.id.ibTimeTask)
    ImageView ibTimeTask;

    private TextView tvRainbowNum;
    private BottomSheetDialog reportDialog;
    private BottomSheetDialog switchGameDialog;
    User user;
    private Queue<GiftAttachment> msgQueue = new LinkedBlockingDeque();

    private boolean isDialogShowing;
    public static final long POST_DELAY_TIME = 3500;
    public static final long POST_DELAY_TIME_2 = 3500;
    private static long postDelayTime = 0;
    private int bigGiftResourceId = 0;
    private int giftPostion = 0;   //距离顶部的位置
    private int giftGravityType = 0;//对齐方式
    private long lastClickTime;
    private ButtomDialog dialog;
    private List<DayTaskData> taskDatas = new ArrayList<>();
    private TaskAdatpter adatpter;
    private List<DayTaskData> missionDatas;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_chatroom;
    }

    @Override
    public void initViews(View root) {
        msgQueue.clear();
        mHandler = new ChatHandler(this);
        user = UserProxy.getUser();
        initViewDisplay();
        piaoPingViews.clear();
        parentFragment = (FragmentLayer) getParentFragment();
        presenter = new ChatRoomPresenter(this);
        presenter.getGameList();
        chatRoomID = getArguments().getString("chatroomId");
        initInputDialog();
        chatItemAdapter = new ChatItemAdapter(chatMessages, mActivity, this);
        lvmessage.setAdapter(chatItemAdapter);
        lvmessage.setOnItemClickListener((parent, v, p, id) -> {
            Object o = chatMessages.get(p);
            if (o instanceof ChatRoomMessage) {
                ChatRoomMessage message = (ChatRoomMessage) o;
                String userID = message.getFromAccount();
                if (TextUtil.isEmpty(userID)) return;
//                if (userID.contains(UserProxy.getUser().getUserId())) return;
                userID = userID.replaceAll("test_", "");
                presenter.getUserInfo(userID);
            }
        });
        memberAdapter = new MemberAdapter(chatRoomMembers, mActivity);
        lvAudience.setOnItemClickListener((parent, v, p, id) -> {
            presenter.getUserInfo(chatRoomMembers.get(p).getAccount().replace("test_", ""));
        });

        lvAudience.setAdapter(memberAdapter);

        NimHelper.queryChatRoomInfo(chatRoomID);

        NimHelper.enterChatRoom(chatRoomID, new EnterChatRoomCallback() {
            @Override
            public void enterSuccess(Object param) {
//                L.e(TAG, "success  " + param.toString());
                CustomMessage msg = new CustomMessage();
                msg.setContent("温馨提示：彩虹直播的互动仅供娱乐，请大家文明观看直播，理性参与游戏，适度娱乐，如有发现相关违规行为，请联系官方客服举报。查证属实的，彩虹将给予奖励。");
                msg.msgType = CustomMessage.MsgType.SYSTEM;
                chatMessages.add(msg);
                chatItemAdapter.notifyDataSetChanged();
            }

            @Override
            public void enterFaild(int code) {
                L.e(TAG, "onFailed  " + code);
            }

            @Override
            public void enterException(Throwable exception) {
                L.e(TAG, "onException  " + exception);
            }
        });


        if (llgiftcontent != null)
            llgiftcontent.showGift();
        NimHelper.getChatRoomMember(chatRoomID,
                FragmentChatRoom.this
        );
        NimHelper.registerMsgObserver(FragmentChatRoom.this, true);
        root.setOnTouchListener(this);
        giftView.setSendGiftListner(this);
        giftView.setGiftAnimationListener(this);
        minaThread = new Thread(() -> {
            MinaHelper.getInstance().connect(this, false);
        });
        minaThread.start();
        //    piaoPingView.start();

        initUserCard();

        initAssistanceDialog();
        initIntroduceGameDialog();
        initDailyDialog();
        initCloseGameDialog();
        UserProxy.addListener(this);
        Observerable.getInstance().subscribe(ObserverableType.SHARE, this);
        Observerable.getInstance().subscribe(ISBANKER, this);
        Observerable.getInstance().subscribe(EXITLIVEROOM, this);
        Observerable.getInstance().subscribe(GETBANKERINFO, this);
    }

    /*初始化某些控件的显示情况*/
    private void initViewDisplay() {
        if (mActivity instanceof LiveRoomActivity) {
            imgMeiyan.setVisibility(View.GONE);
            ivExit.setVisibility(View.INVISIBLE);
            postDelayTime = POST_DELAY_TIME;
        } else {
            gameID = ((PlayLiveRoomActivity) mActivity).getGameId();
            liveID = Integer.parseInt(user.getUserInfo().getLiveId());
            shareInfo = ((PlayLiveRoomActivity) mActivity).getShareInfo();
            imgMeiyan.setVisibility(View.VISIBLE);
//            ivShare.setVisibility(View.GONE);
            ((RelativeLayout.LayoutParams) ivShare.getLayoutParams()).addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            ivHelp.setVisibility(View.GONE);
            imgChat.setVisibility(View.GONE);
            tvFollow.setVisibility(View.GONE);
            imgGift.setVisibility(View.GONE);
            ivCamera.setVisibility(View.VISIBLE);
            ivGame.setVisibility(View.VISIBLE);
            ivExit.setVisibility(View.VISIBLE);
            tvRank.setText("魅力值：" + FormatUtil.formatDealTotal(user.getUserInfo().getCharmtotalvalue()) + "");
            tvID.setText(user.getUserId());
            tvNickName.setText(user.getUserInfo().getNickname());
            GlideUtil.load(this, user.getUserInfo().getIcon(), imgHeader);
            if (((PlayLiveRoomActivity) mActivity).getBeautyState()) {
                imgMeiyan.setImageResource(R.drawable.icon_meiyan);
            } else {
                imgMeiyan.setImageResource(R.drawable.icon_meiyan_close);
            }
            postDelayTime = POST_DELAY_TIME_2;
        }
        initDailyShow();
        if (gameID == 0) {
            llChat.setTranslationY(DeviceUtils.dp2px(mActivity, 200));
        } else {
            llChat.setTranslationY(DeviceUtils.dp2px(mActivity, 0));
        }
    }

    public void setChatViewLoacation(int ty) {
        if (llChat != null)
            llChat.setTranslationY(DeviceUtils.dp2px(mActivity, ty));
    }

    /*日常福利显示*/
    private void initDailyShow() {
        String prefix = UserProxy.getUser().getUserId();
        if (UserProxy.getUser().getUserInfo().getGetSweetsCount() >= 5) {
            llDaily.setVisibility(View.GONE);
        } else {
            llDaily.setVisibility(View.VISIBLE);
        }
        if (liveDetail != null && liveDetail.getInfo().getGetAllSweets() == 1) {
            llDaily.setVisibility(View.GONE);
        }
        if (llDaily.getVisibility() == View.VISIBLE) {
            long startTime = PreferenceUtils.getLong(prefix + "_START_TIME");
            long currentTime = System.currentTimeMillis();
            if (currentTime - startTime >= 1000 * 60 * 5) {
                tvDailyTime.setText("可领取");
            } else {
                mHandler.removeMessages(CODE_DAILY);
                tvDailyTime.setText(FormatUtil.formatTime(5 * 1000 * 60 - currentTime + startTime, "mm:ss"));
                Message msg = mHandler.obtainMessage();
                msg.obj = 5 * 1000 * 60L - currentTime + startTime;
                msg.what = CODE_DAILY;
                mHandler.sendMessage(msg);
            }
        }
    }

    /*领取日常金币*/
    private void getDailyGold(int count) {
        String prefix = UserProxy.getUser().getUserId();
        mHandler.removeMessages(CODE_DAILY);
        info = user.getUserInfo();
        info.setGetSweetsCount(count);
        user.setUserInfo(info);
        UserProxy.setUser(user);
        if (count >= 5) {
            PreferenceUtils.putLong(prefix + "_START_TIME", System.currentTimeMillis());
            llDaily.setVisibility(View.GONE);
        } else {
            PreferenceUtils.putLong(prefix + "_START_TIME", System.currentTimeMillis());
            showToast("领取成功");
            Message msg = mHandler.obtainMessage();
            msg.obj = 5 * 60 * 1000L;
            msg.what = CODE_DAILY;
            mHandler.sendMessage(msg);
        }
    }

    private void initShareInfo(ShareData shareData) {
        if (shareInfo == null) {
            shareInfo = new ShareInfo();
        }
        String url = shareData.getUrl();
        if (!url.startsWith("http")) {
            url = "http://" + url;
        }
        shareInfo.setWebUrl(url);
        if (liveDetail != null && !TextUtil.isEmpty(liveDetail.getInfo().getLiveIcon())) {
            shareInfo.setShareImageUrl(liveDetail.getInfo().getLiveIcon());
        }
        shareInfo.setContent(shareData.getContent());
        shareInfo.setTitle(shareData.getTitle());
        shareInfo.setThumb(R.drawable.default_img);
    }


    /*初始化帮助对话框*/
    private void initAssistanceDialog() {
        if (assictanceDialog == null) {
            View view = LayoutInflater.from(mActivity).inflate(R.layout.layout_game_help, null);
            assictanceDialog = new CustomDialog(mActivity, view);
            view.findViewById(R.id.ivCancel).setOnClickListener(
                    (v) -> assictanceDialog.hide()
            );
            assictanceDialog.hide();
        }
    }

    private void showAssistanceDialog() {
        TextView tvIntroduce = (TextView) assictanceDialog.findViewById(R.id.tvGameIntroduce);
        TextView tvIntroducePlay = (TextView) assictanceDialog.findViewById(R.id.tvGameIntroducePlay);
        if (gameID == 1) {
            tvIntroduce.setText(introduceNiuniu);
            tvIntroducePlay.setText(introducePlayNiuniu);
            assictanceDialog.show();
        } else if (gameID == 2) {
            tvIntroduce.setText(introduceCatMouse);
            tvIntroducePlay.setText(introducePlayCatmouse);
            assictanceDialog.show();
        } else if (gameID == 3) {
            tvIntroduce.setText(introduceSanguo);
            tvIntroducePlay.setText(introducePlaySanguo);
            assictanceDialog.show();
        }

    }

    /*初始化游戏介绍对话框 （游戏切换）*/
    private void initIntroduceGameDialog() {
        if (!(mActivity instanceof PlayLiveRoomActivity)) {
            return;
        }
        if (introduceGameDialog == null) {
            View view = LayoutInflater.from(mActivity).inflate(R.layout.layout_game_introduce, null);
            introduceGameDialog = new CustomDialog(mActivity, view);
            view.findViewById(R.id.tvCancel).setOnClickListener((v) -> introduceGameDialog.hide());
            introduceGameDialog.hide();
            tvGameIntroduce = (TextView) view.findViewById(R.id.tvGameIntroduce);
            tvGameIntroducePlay = (TextView) view.findViewById(R.id.tvGameIntroducePlay);
        }
    }

    private void showGameIntroduceDialog(int gameID) {
        if (introduceGameDialog != null) {
            switch (gameID) {
                case 1: // 牛牛
                    tvGameIntroduce.setText(introduceNiuniu);
                    tvGameIntroducePlay.setText(introducePlayNiuniu);
                    break;
                case 2: //猫鼠
                    tvGameIntroduce.setText(introduceCatMouse);
                    tvGameIntroducePlay.setText(introducePlayCatmouse);
                    break;
            }
            introduceGameDialog.show();
            introduceGameDialog.findViewById(R.id.tvSure).setOnClickListener(
                    (v) -> {
                        if (((PlayLiveRoomActivity) mActivity).getGameId() == 0) { //没游戏
                            ((PlayLiveRoomActivity) mActivity).setGameID(gameID);
                            parentFragment.switchGame(gameID);
                        } else {
                            sendChangeGameMsg2Server(gameID);
                        }

                        introduceGameDialog.hide();

                    }
            );
        }
    }

    /*初始化关闭游戏提示对话框*/
    private void initCloseGameDialog() {
        if (closeGameDialog == null) {
            View view = View.inflate(mActivity, R.layout.layout_choose_dialog, null);
            closeGameDialog = new CustomDialog(mActivity, view);
            TextView tvContent = (TextView) view.findViewById(R.id.tvContent);
            TextView tvTitle = (TextView) view.findViewById(R.id.tvTitle);
            tvTitle.setText("确认关闭游戏");
            tvContent.setText(hintCloseGame);
            TextView tvSure = (TextView) view.findViewById(R.id.btnSure);
            tvSure.setText("确定");
            view.findViewById(R.id.btnCancel).setOnClickListener((v) -> closeGameDialog.hide());
            closeGameDialog.hide();
        }
    }

    private void showCloseGameDialog(int gameID) {
        if (closeGameDialog != null) {
            closeGameDialog.show();
            closeGameDialog.findViewById(R.id.btnSure)
                    .setOnClickListener((v) -> {
                        closeGameDialog.hide();
                        sendCloseGameMsg2Server(gameID);
                    });
        }
    }

    /*初始化日常福利对话框*/
    private void initDailyDialog() {
        if (dailyDialog == null) {
            View view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_daily, null);
            dailyDialog = new CustomDialog(mActivity, view);
            view.findViewById(R.id.ivCancel).setOnClickListener(
                    (v) -> dailyDialog.hide()
            );
            tvCount = (TextView) view.findViewById(R.id.tvCount);
            tvTimes = (TextView) view.findViewById(R.id.tvTimes);
            dailyDialog.hide();
        }
    }

    private void showDailyDialog(int count) {
        tvCount.setText("x30");
        if (count < 5)
            tvTimes.setText(Html.fromHtml(getResources().getString(R.string.format_daily, 5 + "", (5 - count) + "")));
        else
            tvTimes.setText(Html.fromHtml(getResources().getString(R.string.format_daily_zero, "5")));
        dailyDialog.show();
        tvCount.postDelayed(() -> dailyDialog.hide(), 2000);
    }

    /**
     * 聊天时消息
     */
    @Override
    public void onReceive(ChatRoomMessage message) {
        if (message.getAttachment() != null) {
            if (message.getAttachment() instanceof GiftAttachment) { //礼物
                GiftAttachment giftAttachment = (GiftAttachment) message.getAttachment();
                int level = 0;
                if (message.getRemoteExtension().containsKey("level")) {
                    level = (int) message.getRemoteExtension().get("level");
                }
                setDiffGift(giftAttachment);
            } else if (message.getAttachment() instanceof ChatRoomNotificationAttachment) { //通知
                ChatRoomNotificationAttachment attachment = (ChatRoomNotificationAttachment) message.getAttachment();
                if (attachment.getType() == NotificationType.ChatRoomMemberExit) {
                    for (ChatRoomMember member : chatRoomMembers) {
                        if (member.getAccount().equals(attachment.getOperator())) {
                            chatRoomMembers.remove(member);
                            memberAdapter.notifyDataSetChanged();
                            break;
                        }
                    }
                    return;
                } else if (attachment.getType() == NotificationType.ChatRoomMemberIn) {
                    int level = 0;
                    if (attachment != null && attachment instanceof ChatRoomNotificationAttachment) {
                        if (attachment.getExtension() != null && attachment.getExtension().containsKey("level")) {
                            level = (int) attachment.getExtension().get("level");
                        }
                    }
                    NimHelper.getChatRoomMember(level, chatRoomID, this, attachment.getOperator());
                }
            }
        } else {
            //全平台通知
            String giftName = null;
            String liveId = null;
            String senderName = null;
            String chatroomId = null;
            String type = null;
            String winnerName = null;
            String winSweetNum = null;
            String object = null;
            //后面新增 receiverName
            Map<String, Object> map = message.getRemoteExtension();
            L.e(TAG, "全平台通知" + map.toString());
            if (map != null && map.containsKey("type") && ("1".equals(map.get("type").toString()) || ("2").equals
                    (map.get("type")))) {
                SpecialGift specialGift = new SpecialGift();
                AllPlatformData data = new AllPlatformData();
                try {
                    type = (String) map.get("type");
                    if (!TextUtil.isEmpty(type)) {
                        data.setAllPlatformNoticeType(Integer.parseInt(type));
                    }
                    if (map.containsKey("giftName")) {
                        giftName = map.get("giftName").toString();
                        data.setGiftName(giftName);
                    }
                    if (map.containsKey("winnerName")) {
                        winnerName = map.get("winnerName").toString();
                        data.setWinnerName(winnerName);
                    }
                    if (map.containsKey("winSweetNum")) {
                        winSweetNum = map.get("winSweetNum").toString();
                        data.setWinSweetNum(winSweetNum);
                    }
                    if (map.containsKey("liveId")) {
                        liveId = map.get("liveId").toString();
                        data.setLiveId(liveId);
                    }
                    if (map.containsKey("senderName")) {
                        senderName = map.get("senderName").toString();
                        data.setSenderName(senderName);
                    }
                    if (map.containsKey("chatroomId")) {
                        chatroomId = map.get("chatroomId").toString();
                        data.setChatroomId(chatroomId);
                    }
                    specialGift.setAllPlatformData(data);
                    showAllPlatformNotice(specialGift);
                    return;
                } catch (Exception e) {
                    e.toString();
                }
            }

        }
        chatMessages.add(message);
        chatItemAdapter.notifyDataSetChanged();

    }

    private void setDiffGift(GiftAttachment giftAttachment) {
        int giftId = Integer.parseInt(giftAttachment.getGiftID());
        if (giftId == 6 || giftId == 7 || giftId == 8) {
            if (msgQueue.isEmpty()) {
                msgQueue.add(giftAttachment);
                mHandler.removeMessages(CODE_BIG_GIFT);
                Message msg = mHandler.obtainMessage();
                msg.what = CODE_BIG_GIFT;
                msg.obj = 1;
                mHandler.sendMessage(msg);
            } else {
                msgQueue.add(giftAttachment);
            }
        }
        if (giftAttachment.getGiftType() == COMMON_PIAO_PING_VIEW) {
            SpecialGift specialGift = new SpecialGift();
            specialGift.setGiftName(giftAttachment.getGiftName());
            specialGift.setFrom(giftAttachment.getSenderName());
            specialGift.setGiftIcon(giftAttachment.getGiftShowImage());
            specialGift.setType(giftAttachment.getGiftType());
            specialGift.setSenderIcon(giftAttachment.getHeadIcon());
            setPiaoPingView(specialGift);
        } else if (giftAttachment.getGiftType() == DOUBLE_HIT_GIFT) {
            Gift gift = new Gift();
            gift.setNoFrameIcon(giftAttachment.getGiftShowImage());
            gift.setName(giftAttachment.getGiftName());
            gift.setNum(Integer.parseInt(giftAttachment.getGiftNum()));
            gift.setUserId(giftAttachment.getSenderID());
            gift.setSenderIcon(giftAttachment.getHeadIcon());
            gift.setFromNick(giftAttachment.getSenderName());
            if (llgiftcontent == null) return;
            llgiftcontent.addGift(gift);
        }
    }

    @Override
    public void commentHandle(IMMessage message) {

    }

    public void memberIn(int level, String nickName) {
        SpecialGift specialGift = new SpecialGift();
        specialGift.setFrom(nickName);
        specialGift.setUserLevel(level);
        specialGift.setType(MEMBER_IN);
        setPiaoPingView(specialGift);
    }

    @OnClick({R.id.imgChat, R.id.imgGift, R.id.ivExit, R.id.ivShare, R.id.tvFollow, R.id.ivHelp, R.id.imgAnchorHeader
            , R.id.ivMeiyan, R.id.ivCamera, R.id.ivGame
            , R.id.llDaily, R.id.tvRank, R.id.llTask})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imgChat:
                showInputLayout(true);
                showKeyboard();
                giftView.hide();
                lvmessage.setVisibility(View.VISIBLE);
                break;
            case R.id.imgGift:
                if (mActivity instanceof LiveRoomActivity) {
                    if (llChat.getTranslationY() == DeviceUtils.dp2px(mActivity, 200)) {
                        ObjectAnimator animator = ObjectAnimator.ofFloat(llChat, "translationY", DeviceUtils.dp2px(mActivity, 200), 0);
                        // animator.start();
                    }
                    hideKeyboard();
                    showInputLayout(false);
                    giftView.show();
                    if (llRewards.getVisibility() == View.VISIBLE)
                        llRewards.setVisibility(View.INVISIBLE);
                    lvmessage.setVisibility(View.INVISIBLE);
                    if (UserProxy.getUser() == null) {
                        giftView.setCoinsCount(0);
                    } else {
                        giftView.setCoinsCount(UserProxy.getUser().getUserInfo().getRainbowSweet());
                    }
                    rlAction.setVisibility(View.INVISIBLE);
                    parentFragment.hideGame();
                }
                break;
            case R.id.ivExit:
                mActivity.onBackPressed();
                break;
            case R.id.ivShare:
                showShareDialog();
                break;
            case R.id.tvFollow:
                if (liveDetail == null) return;
                info = new UserInfo();
                presenter.subscribeUp(liveDetail.getInfo().getUserId());
                break;
            case R.id.ivHelp:
                showAssistanceDialog();
                break;
            case R.id.imgAnchorHeader:
                if (liveDetail == null) return;
                presenter.getUserInfo(liveDetail.getInfo().getUserId());
                break;
            case R.id.ivMeiyan:
                ((PlayLiveRoomActivity) mActivity).openOrCloseBeauty();
                if (((PlayLiveRoomActivity) mActivity).getBeautyState()) {
                    imgMeiyan.setImageResource(R.drawable.icon_meiyan);
                } else {
                    imgMeiyan.setImageResource(R.drawable.icon_meiyan_close);
                }
                break;
            case R.id.llDaily:
                if (tvDailyTime.getText().equals("可领取")) {
                    presenter.getDaily(30);
                }
                break;
            case R.id.tvRank:
                Intent intent = new Intent();
                intent.setClass(mActivity, ContributionsActivity.class);
                if (mActivity instanceof LiveRoomActivity) {
                    intent.putExtra("upUserId", liveDetail.getInfo().getUserId());
                } else {
                    intent.putExtra("upUserId", UserProxy.getUser().getUserId());
                }
                jumpToActivity(intent);
                break;
            case R.id.ivCamera:
                ((PlayLiveRoomActivity) mActivity).switchCamera();
                break;
            case R.id.ivGame:
                initGameSwitchDialog();
                break;
            case R.id.llTask:
                presenter.getMissionList();
                break;
        }
    }

    private void showTaskDialog(List<DayTaskData> datas) {
        if (dialog == null) {
            dialog = new ButtomDialog(mActivity, R.style.Dialog);
            View contentView = View.inflate(mActivity, R.layout.dialog_day_task, null);
            dialog.setContentView2(contentView);
            tvRainbowNum = (TextView) contentView.findViewById(R.id.tvRainbowNum);
            ListView lvTask = (ListView) contentView.findViewById(R.id.lvTask);
            adatpter = new TaskAdatpter(mActivity);
            adatpter.setListener(this);
            adatpter.setDatas(datas);
            lvTask.setAdapter(adatpter);
        } else {
            if (adatpter != null) {
                adatpter.setDatas(datas);
                adatpter.notifyDataSetChanged();
            }
        }
        tvRainbowNum.setText(UserProxy.getUser().getUserInfo().getRainbowSweet() + "");
        if (!dialog.isShowing()) {
            dialog.show();
        }
    }

    private void showReportDialog(UserInfo info) {
        if (reportDialog == null) {
            CustomBottomSheetDialog dialog = new CustomBottomSheetDialog(mActivity);
            View contentView = View.inflate(mActivity, R.layout.bottom_report_dialog, null);
            reportDialog = dialog.getInstance(contentView);
            contentView.findViewById(R.id.tvReport1).setOnClickListener(clickListener);
            contentView.findViewById(R.id.tvReport2).setOnClickListener(clickListener);
            contentView.findViewById(R.id.tvReport3).setOnClickListener(clickListener);
            contentView.findViewById(R.id.tvReport4).setOnClickListener(clickListener);
            contentView.findViewById(R.id.tvReport5).setOnClickListener(clickListener);
            contentView.findViewById(R.id.tvCancle).setOnClickListener(clickListener);
        }
        reportDialog.show();
    }

    /*选择游戏*/
    private void initGameSwitchDialog() {
        if (switchGameDialog == null) {
            CustomBottomSheetDialog dialog = new CustomBottomSheetDialog(mActivity, R.style.BG_TRANPARENT);
            View contentView = View.inflate(mActivity, R.layout.dialog_switch_game, null);
            switchGameDialog = dialog.getInstance(contentView);
            switchGameDialog.getWindow().setDimAmount(0);
            switchGameDialog.getWindow().findViewById(R.id.design_bottom_sheet).setBackgroundResource(R.color.transparent);
            lvGame = (HorizontalListView) contentView.findViewById(R.id.lvGame);
            gameListAdapter = new GameListAdapter(gameList, mActivity);
            lvGame.setAdapter(gameListAdapter);
        }
        gameID = parentFragment.getGameID();
        filterGameList();
        gameListAdapter.notifyDataSetChanged();
        switchGameDialog.show();
        lvGame.setOnItemClickListener((parent, v, pos, id) -> {
            if (pos == gameList.size() - 1) return;
            GameInfo game = gameList.get(pos);
            if (game.isSelected()) {
                /*game.setSelected(false);
                gameListAdapter.notifyDataSetChanged();*/
                showCloseGameDialog(0);
            } else {
                /*gameID = game.getId();
                filterGameList();
                gameListAdapter.notifyDataSetChanged();*/
                showGameIntroduceDialog(game.getId());
            }
            switchGameDialog.hide();
        });
    }

    private void filterGameList() {
        for (GameInfo gameInfo : gameList) {
            if (gameInfo.getId() == gameID) {
                gameInfo.setSelected(true);
                continue;
            }
            gameInfo.setSelected(false);
        }
    }


    View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (reportDialog != null && reportDialog.isShowing()) {
                reportDialog.dismiss();
            }
            if (info == null) {
                return;
            }
            switch (v.getId()) {
                case R.id.tvCancle:
                    break;
                case R.id.tvReport1:
                    presenter.inform(info.getId(), String.valueOf(0));
                    break;
                case R.id.tvReport2:
                    presenter.inform(info.getId(), String.valueOf(1));
                    break;
                case R.id.tvReport3:
                    presenter.inform(info.getId(), String.valueOf(2));
                    break;
                case R.id.tvReport4:
                    presenter.inform(info.getId(), String.valueOf(3));
                    break;
                case R.id.tvReport5:
                    presenter.inform(info.getId(), String.valueOf(4));
                    break;
            }
        }
    };

    private void showShareDialog() {
        if (shareDialog == null) {
            shareDialog = new ShareDialog(getContext(), R.style.Dialog);
            shareDialog.setOnItemClick(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (shareInfo == null) return;
                    switch (v.getId()) {
                        case R.id.llSina:
                            ShareUtils.shareToSocial(mActivity, SHARE_MEDIA.SINA, shareInfo);
                            break;
                        case R.id.llWeChat:
                            ShareUtils.shareToSocial(mActivity, SHARE_MEDIA.WEIXIN, shareInfo);
                            break;
                        case R.id.llFriend:
                            ShareUtils.shareToSocial(mActivity, SHARE_MEDIA.WEIXIN_CIRCLE, shareInfo);
                            break;
                        case R.id.llQQ:
                            ShareUtils.shareToSocial(mActivity, SHARE_MEDIA.QQ, shareInfo);
                            break;
                    }
                    if (shareDialog != null && shareDialog.isShowing()) {
                        if (mActivity instanceof PlayLiveRoomActivity) {
                            ((PlayLiveRoomActivity) mActivity).setShare(true);
                        }
                        shareDialog.dismiss();
                    }
                }
            });
            shareDialog.show();
        } else {
            shareDialog.show();
        }
    }

    /**
     * 显示软键盘并因此头布局
     */
    private void showKeyboard() {
        inputDialog.getWindow().getDecorView().postDelayed(() -> {
            editChat.requestFocus();
            InputMethodManager imm = (InputMethodManager)
                    getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(editChat, InputMethodManager.SHOW_FORCED);
            llChat.setTranslationY(DeviceUtils.dp2px(mActivity, -76));
        }, 100);

    }

    /**
     * 隐藏软键盘并显示头布局
     */
    public void hideKeyboard() {
        editChat.clearFocus();
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(editChat.getWindowToken(), 0);
        if (parentFragment.isShowGame() || llChat.getTranslationY() == 0) {
            llChat.setTranslationY(0);
        } else {
            llChat.setTranslationY(DeviceUtils.dp2px(mActivity, 200));
        }

    }

    private void showInputLayout(boolean show) {
        if (show) {
            inputDialog.show();
        } else {
            inputDialog.hide();
        }
    }

    InputDialog inputDialog;

    private void initInputDialog() {
        View llInput = LayoutInflater.from(mActivity)
                .inflate(R.layout.layout_chat_input, null);
        editChat = (InputEdittext) llInput.findViewById(R.id.editChat);
        editChat.setBackListener((v) -> {
            showInputLayout(false);
            hideKeyboard();
        });
        TextView tvSend = (TextView) llInput.findViewById(R.id.tvSend);
        tvSend.setOnClickListener((v) -> sendTextMsg());
        if (inputDialog == null) {
            inputDialog = new InputDialog(mActivity, llInput) {
                @Override
                public void dismiss() {
                    hideKeyboard();
                    super.dismiss();
                }

                @Override
                public void hide() {
                    hideKeyboard();
                    super.hide();
                }
            };
            inputDialog.hide();
        }
    }

    private void sendTextMsg() {
        if (TextUtil.isEmpty(editChat.getText().toString())) {
            showToast("说点什么吧");
            return;
        } else {
            User u = UserProxy.getUser();
            ChatRoomMessage message = ChatRoomMessageBuilder.createChatRoomTextMessage(chatRoomID,
                    editChat.getText().toString());
            Map<String, Object> extention = new HashMap<>();
            extention.put("nickname", u.getUserInfo().getNickname());
            message.setRemoteExtension(extention);
            sendMessage(chatRoomID, message);
            editChat.setText("");
            showInputLayout(false);
            hideKeyboard();
        }
    }

    /*发送通知信息*/
    public void sendNotifyMessage(String content) {
        sendNotifyMessage(content, true);
    }

    /*发送通知信息*/
    public void sendNotifyMessage(String content, boolean send) {
        ChatRoomMessage message = ChatRoomMessageBuilder.createChatRoomTextMessage(chatRoomID,
                content);
        Map<String, Object> extention = new HashMap<>();
        extention.put("system", "system");
        message.setRemoteExtension(extention);
        if (send) {
            sendMessage(chatRoomID, message);
        } else {
            chatMessages.add(message);
            chatItemAdapter.notifyDataSetChanged();
        }
    }

    public void sendFollowedMessage() {
        ChatRoomMessage message = ChatRoomMessageBuilder.createChatRoomTextMessage(chatRoomID,
                "关注了该主播");
        Map<String, Object> extention = new HashMap<>();
        extention.put("nickname", user.getUserInfo().getNickname());
        message.setRemoteExtension(extention);
        sendMessage(chatRoomID, message);
    }

    /*手指监听*/
    private int mPosY;


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (!Utils.isFastDoubleClick(lastClickTime)) {
            lastClickTime = System.currentTimeMillis();
            giftView.hide();
        }
        lvmessage.setVisibility(View.VISIBLE);
        rlAction.setVisibility(View.VISIBLE);
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPosY = (int) event.getY();
                break;
            case MotionEvent.ACTION_UP:
                int currentY = (int) event.getY();
                if (currentY - mPosY > ViewConfiguration.get(mActivity).getScaledTouchSlop() &&
                        llChat.getTranslationY() == 0) {//下滑
                    ObjectAnimator animator = ObjectAnimator.ofFloat(llChat, "translationY", 0, DeviceUtils.dp2px(mActivity, 200));
                    animator.start();
                    parentFragment.hideGameWithAnim();
                } else if (mPosY - currentY > ViewConfiguration.get(mActivity).getScaledTouchSlop() &&
                        llChat.getTranslationY() == DeviceUtils.dp2px(mActivity, 200)) {
                    ObjectAnimator animator = ObjectAnimator.ofFloat(llChat, "translationY", DeviceUtils.dp2px(mActivity, 200), 0);
                    animator.start();
                    parentFragment.showGameWithAnim();
                }
                break;
        }
        return true;
    }

    @Override
    public void sendGift(Gift g, int giftType) {
        if (isBanker && user.getUserInfo().getRainbowSweet() < 30000) {
            showSnackbar(getRootView(mActivity), "当前余额不足（已上庄）");
        } else {
            sendGiftMsgToServer(g);
        }

    }

    /**
     * 发送礼物消息
     *
     * @param
     */
    private void sendGiftMessage(Gift gift) {
        mActivity.runOnUiThread(() -> giftView.sendGiftSuccess(gift));
        if ((System.currentTimeMillis() - gift.getStartTime()) / 1000 < 10 || gift.getStartTime() == 0) {
            gift.setDoubleHitNum(gift.getDoubleHitNum() + 1);
        } else {
            gift.setDoubleHitNum(1);
        }
        GiftAttachment giftAttachment = new GiftAttachment();
        giftAttachment.setGiftID(gift.getId() + "");
        giftAttachment.setGiftName(gift.getName());
        giftAttachment.setGiftNum(gift.getDoubleHitNum() + "");
        giftAttachment.setGiftShowImage(gift.getIcon());
        giftAttachment.setGiftType(gift.getType());
        giftAttachment.setSenderName(UserProxy.getUser().getUserInfo().getNickname());
        giftAttachment.setHeadIcon(UserProxy.getUser().getUserInfo().getIcon());
        sendGiftMessage(giftAttachment);
    }


    /**
     * 发送礼物
     *
     * @param giftAttachment 礼物
     */
    public void sendGiftMessage(GiftAttachment giftAttachment) {
        if (giftAttachment != null) {
            mChatRoomMessage = ChatRoomMessageBuilder.createChatRoomCustomMessage(chatRoomID, giftAttachment);
            sendMessage(chatRoomID, mChatRoomMessage);
            bSendGiftMessage = true;
            mActivity.runOnUiThread(() -> setDiffGift(giftAttachment));
        }
    }

    private Map<Integer, PiaoPingView> setPiaoPingView(SpecialGift specialGift) {
        mActivity.runOnUiThread(() -> {
            switch (specialGift.getType()) {
                case NOTICE_PIAO_PING_VIEW:
                    if (!judge(NOTICE_PIAO_PING_VIEW)) {
                        initPiaoPingView(specialGift);
                    } else {
                        findPiaoPingView(specialGift);
                    }
                    break;
                case MEMBER_IN:
                    if (!judge(MEMBER_IN)) {
                        initPiaoPingView(specialGift);
                    } else {
                        findPiaoPingView(specialGift);
                    }
                    break;
                case COMMON_PIAO_PING_VIEW:
                    if (!judge(COMMON_PIAO_PING_VIEW)) {
                        initPiaoPingView(specialGift);
                    } else {
                        findPiaoPingView(specialGift);
                    }
                    break;

            }
        });

        return piaoPingViews;
    }

    /**
     * 如果hasMap里面已经有此类型的PiaoPingView就在hasmap里面拿取，并添加到PiaoPingView队列里面
     *
     * @param specialGift
     */
    private void findPiaoPingView(SpecialGift specialGift) {
        PiaoPingView piaoPingView = (PiaoPingView) piaoPingViews.get(specialGift.getType());
        piaoPingView.add(specialGift);
    }

    /**
     * 往rlParent里面动态的添加PiaoPingView 并根据礼物类型去设置不同的位置
     *
     * @param specialGift
     */
    private void initPiaoPingView(SpecialGift specialGift) {
        L.e(TAG, "initPiaoPingView");
        PiaoPingView piaoPingView = new PiaoPingView(mActivity);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(3600, ViewGroup.LayoutParams.WRAP_CONTENT);
        switch (specialGift.getType()) {
            case COMMON_PIAO_PING_VIEW:
                layoutParams.topMargin = DeviceUtils.dp2px(mActivity, 124);
                break;
            case NOTICE_PIAO_PING_VIEW:
                layoutParams.topMargin = DeviceUtils.dp2px(mActivity, 78);
                break;
            case MEMBER_IN:
                layoutParams.topMargin = DeviceUtils.dp2px(mActivity, 280);
                break;
        }
        piaoPingView.setLayoutParams(layoutParams);
        piaoPingView.start();
        if (rlParent != null) {
            rlParent.addView(piaoPingView);
            piaoPingView.add(specialGift);
            piaoPingViews.put(specialGift.getType(), piaoPingView);
        }
    }

    /**
     * 6 跑车 7女神 8求婚
     *
     * @param giftAttachment
     */
    private void showBigGift(GiftAttachment giftAttachment) {
        ImageView imageView = new ImageView(mActivity);
        switch (Integer.parseInt(giftAttachment.getGiftID())) {
            case 6:
                bigGiftResourceId = R.drawable.anim_gift_car;
                giftPostion = 300;
                giftGravityType = RelativeLayout.ALIGN_START;
                break;
            case 7:
                bigGiftResourceId = R.drawable.anim_goddess_gift;
                giftPostion = 250;
                giftGravityType = RelativeLayout.CENTER_HORIZONTAL;
                break;
            case 8:
                bigGiftResourceId = R.drawable.anim_marry_gift;
                giftPostion = 250;
                giftGravityType = RelativeLayout.CENTER_HORIZONTAL;
                break;
        }
        MyAnimationDrawable.animateRawManuallyFromXML(bigGiftResourceId,
                imageView, new Runnable() {

                    @Override
                    public void run() {
                        // 动画开始时回调
                    }
                }, new Runnable() {

                    @Override
                    public void run() {
                        // TODO onComplete
                        // 动画结束时回调
                        imageView.clearAnimation();
                        imageView.setVisibility(View.GONE);
                        if (rlParent != null) {
                            rlParent.removeView(imageView);
                        }
                    }
                });
        RelativeLayout.LayoutParams gR = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        gR.topMargin = DeviceUtils.dp2px(mActivity, giftPostion);
        gR.addRule(giftGravityType);
        if (rlParent != null) {
            rlParent.addView(imageView, gR);
        }
    }

    /**
     * 判断hasmap里面是否PiaoPingView
     *
     * @param type
     * @return
     */
    private boolean judge(int type) {
        if (piaoPingViews != null) {
            if (piaoPingViews.containsKey(type)) {
                return true;
            } else {
                return false;
            }

        } else {
            return false;
        }
    }

    private void sendMessage(String roomId, ChatRoomMessage msg) {
        Map<String, Object> ex = msg.getRemoteExtension();
        if (ex == null) ex = new HashMap<>();
        ex.put("level", UserProxy.getUser().getUserInfo().getLv());
        msg.setRemoteExtension(ex);

        NimHelper.sendMessage(roomId, msg, sendMsgCallback);
    }

    private SendMsgCallback sendMsgCallback = new SendMsgCallback() {
        @Override
        public void sendSuccess(ChatRoomMessage message) {
            chatMessages.add(message);
            chatItemAdapter.notifyDataSetChanged();
        }

        @Override
        public void sendFaild(int code) {
            if (code == 13004) {
                showSnackbar(getRootView(mActivity), "你已经被禁言，暂时不能说话");
            }
        }

        @Override
        public void sendException(Throwable throwable) {

        }
    };


    @Override
    public void onDestroy() {
        exitChatRoom();
        for (Map.Entry<Integer, PiaoPingView> entry : piaoPingViews.entrySet()) {
            entry.getValue().release();
        }
        editChat.removeCallback();
        inputDialog.dismiss();
        sendOfflineMsg2Server();
        NimHelper.registerMsgObserver(this, false);
        NimHelper.exitChatRoom(chatRoomID);
        MinaHelper.getInstance().removeCallback(this);
        assictanceDialog.dismiss();
        if (introduceGameDialog != null) {
            introduceGameDialog.dismiss();
        }
        closeGameDialog.dismiss();
        dailyDialog.dismiss();
        userCard.dismiss();
        mHandler.removeCallbacksAndMessages(null);
        UserProxy.removeListener(this);
        Observerable.getInstance().unSubscribe(ObserverableType.SHARE, this);
        Observerable.getInstance().unSubscribe(ISBANKER, this);
        Observerable.getInstance().unSubscribe(GETBANKERINFO, this);
        Observerable.getInstance().unSubscribe(EXITLIVEROOM, this);
        super.onDestroy();
    }


/*长连接回调*/

    public void onConnected(IoSession session) {
        L.e(TAG, "connect success");
        if (mActivity instanceof PlayLiveRoomActivity) {
            sendEnterLiveRoomMsg2Server();
        }
    }

    private void sendEnterLiveRoomMsg2Server() {
        if (mActivity instanceof PlayLiveRoomActivity) {
            RainbowMessage.CGEnterLiveRoom.Builder builder = RainbowMessage.CGEnterLiveRoom.newBuilder()
                    .setLiveId(Integer.parseInt((user.getUserInfo().getLiveId())))
                    .setUserId(Integer.parseInt(user.getUserId()));
            Packet packet = Packet.newPbPacket(HOpCodeEx.CGEnterLiveRoom, builder.build().toByteArray());
            packet.setFlag(9);
            packet.setStamp(System.currentTimeMillis());
            packet.setRetCode(0);
            MinaHelper.getInstance().sendMessageToServer(packet);
        } else {
            RainbowMessage.CGEnterLiveRoom.Builder builder = RainbowMessage.CGEnterLiveRoom.newBuilder()
                    .setLiveId(Integer.parseInt(liveDetail.getInfo().getLiveId()))
                    .setUserId(Integer.parseInt(user.getUserId()));
            Packet packet = Packet.newPbPacket(HOpCodeEx.CGEnterLiveRoom, builder.build().toByteArray());
            packet.setFlag(9);
            packet.setStamp(System.currentTimeMillis());
            packet.setRetCode(0);
            MinaHelper.getInstance().sendMessageToServer(packet);
            L.e("服务", " liveid  " + builder.getLiveId());
        }
    }

    @Override
    public void onException(IoSession session, Throwable cause) {
        L.e(TAG, "onException " + cause);
    }


    @Override
    public void onReceiveMessage(IoSession session, Object message) {
        Packet packet = (Packet) message;
        RainbowMessage.GCSendGiftRet giftRet = null;
        try {
            giftRet = RainbowMessage.GCSendGiftRet.parseFrom((byte[]) packet.getData());
        } catch (InvalidProtocolBufferException e) {
            e.printStackTrace();
        }
        switch (packet.getPacketId()) {
            case HOpCodeEx.GCSendGiftRet:
                if (packet.getRetCode() == 0) {
                    L.e(TAG, "发送礼物长连接");
                    sendGiftMessage(findGiftById(giftRet.getGitfId()));
                } else {

                }
                break;
            case HOpCodeEx.GCCloseLiveRet:
                Message msg = mHandler.obtainMessage();
                msg.what = CODE_CLOSE_VIDEO;
                mHandler.sendMessage(msg);
                break;
            case HOpCodeEx.GCCloseGameRet:
                mHandler.sendEmptyMessage(CODE_CLOSE_ALL);
                break;
            case HOpCodeEx.GCChangeGameRet:
                try {
                    RainbowMessage.GCChangeGameRet ret = RainbowMessage.GCChangeGameRet.parseFrom((byte[]) packet.getData());
                    msg = mHandler.obtainMessage();
                    msg.what = CODE_CHANGE_GAME;
                    msg.obj = ret;
                    mHandler.sendMessage(msg);

                } catch (InvalidProtocolBufferException e) {
                    e.printStackTrace();
                }
                break;
            case HOpCodeEx.GCNowCloseGameRet:
                try {
                    RainbowMessage.GCNowCloseGameRet ret = RainbowMessage.GCNowCloseGameRet.parseFrom((byte[]) packet.getData());
                    if (ret.getCode() == 0) {
                        mHandler.sendEmptyMessage(CODE_CLOSE_GAME);
                    }

                } catch (InvalidProtocolBufferException e) {
                    e.printStackTrace();
                }
                break;
            case HOpCodeEx.GCGameStateRet:
                if (!hasGame && mActivity instanceof LiveRoomActivity && parentFragment.getGameID() == 0) {
                    try {
                        RainbowMessage.GCGameStateRet gameStateRet = RainbowMessage.GCGameStateRet.parseFrom((byte[]) packet.getData());
                        parentFragment.switchGame(gameStateRet.getGameId());
                        hasGame = true;
                        L.e(TAG,"CCCCCCCCCCCCCCCCCCCCC     111111111111");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;
            case HOpCodeEx.GCOutLiveRoomRet:
                try {
                    RainbowMessage.GCOutLiveRoomRet liveRoomRet = RainbowMessage.GCOutLiveRoomRet.parseFrom((byte[]) packet.getData());
                    L.e(TAG, "liveRoomRet  " + liveRoomRet.getCode());
                } catch (InvalidProtocolBufferException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

    private void changeGame(RainbowMessage.GCChangeGameRet ret) {
        if (ret.getCode() == 0) { // 返回成功
            if (gameID != 0) {
                int gameId = ret.getGameId();
                Observerable.getInstance().notifyChange(ObserverableType.SWITCHGAME, gameId);
                String gameName = "欢乐牛牛";
                if (gameId == 2) {
                    gameName = "猫和老鼠";
                } else if (gameId == 3) {
                    gameName = "三英战吕布";
                }
                if (mActivity instanceof PlayLiveRoomActivity) {
                    showSnackbar(getRootView(mActivity), "本局游戏结束后自动切换至" + gameName + "游戏");
                    sendNotifyMessage("主播已切换游戏,本局游戏结束后切换至“" + gameName + "”游戏",false);
                } else {
                    sendNotifyMessage("主播已切换游戏,本局游戏结束后切换至“" + gameName + "”游戏",false);
                }
            } else {
                parentFragment.showGame(ret.getGameId());
                closeGame = false;
            }
        } else {
            showSnackbar(getRootView(mActivity), "操作失败，请稍后重试");
        }
    }

    private void showAllPlatformNotice(SpecialGift specialGift) {
        L.e(TAG, "showAllPlatformNotice");
        specialGift.setType(NOTICE_PIAO_PING_VIEW);
        setPiaoPingView(specialGift);
    }

    @Override
    public void onDisConnected(IoSession session) {
        L.e(TAG, "onDisConnected ");
    }
/*----长连接回调 end*/


    /*获取成员信息回调*/
    @Override
    public void getMembers(List<ChatRoomMember> members) {
        for (ChatRoomMember member : members) {
            if (member.getAccount().length() > 20) continue;
            int index = memberExits(member);
            if (index == -1) {
                chatRoomMembers.add(member);
                int level = -1;
                User user = UserProxy.getUser();
                if (member.getAccount().replaceAll("test_", "").equals(user.getUserId())) {
                    level = user.getUserInfo().getLv();
                } else {
                    level = member.getMemberLevel();
                }
                if (level >= 20)
                    memberIn(level, member.getNick());
            } else {
                chatRoomMembers.set(index, member);
            }
        }
        sortChatRoomMember(chatRoomMembers);
        memberAdapter.notifyDataSetChanged();
    }

    private int memberExits(ChatRoomMember member) {
        for (int i = 0; i < chatRoomMembers.size(); i++) {
            if (chatRoomMembers.get(i).getAccount().equals(member.getAccount()))
                return i;
        }
        return -1;
    }

    /*用户卡片*/
    private void initUserCard() {
        if (userCard == null) {
            View v = LayoutInflater.from(mActivity).inflate(R.layout.layout_usercard, null);
            userCard = new CustomDialog(mActivity, v, true);
            cardView = ((ViewGroup) v).getChildAt(0);
            imgCardHeader = (CircleImageView) v.findViewById(R.id.imgHeader);
            tvCardCharmCount = (TextView) v.findViewById(R.id.tvCharmCount);
            tvFansCount = (TextView) v.findViewById(R.id.tvFansCount);
            tvCardId = (TextView) v.findViewById(R.id.tvId);
            tvCardNickName = (TextView) v.findViewById(R.id.tvNickName);
            tvWords = (TextView) v.findViewById(R.id.tvWords);
            tvLevel = (TextView) v.findViewById(R.id.tvLevel);
            tvFollowCount = (TextView) v.findViewById(R.id.tvFollowCount);
            tvCardFollow = (TextView) v.findViewById(R.id.tvFollow);
            tvReport = (TextView) v.findViewById(R.id.tvReport);
            tvHomePage = (TextView) v.findViewById(R.id.tvHomePage);
            spliteLine = v.findViewById(R.id.spliteLine);
            v.findViewById(R.id.ivCancel).setOnClickListener((view) ->
                    userCard.hide());
            userCard.hide();

        }
    }

    @Override
    public void setPresenter(ChatRoomContract.Presenter presenter) {
        super.presenter = presenter;

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showSubscribeResult(int code, String userId) {
        if (code == 0) {
            if (info == null) {
                return;
            }
            info.setIsSubscribe((info.getIsSubscribe() + 1) % 2);
            if (info.getIsSubscribe() == 1) {
                showToast("关注成功");
                Observerable.getInstance().notifyChange(ObserverableType.ATTENTION, 1);
                info.setIsSubscribe(1);
                String upUserID;
                if (mActivity instanceof PlayLiveRoomActivity) {
                    upUserID = UserProxy.getUser().getUserId();
                } else {
                    upUserID = liveDetail.getInfo().getUserId();
                }
                if (!userId.equals(upUserID)) { //是否是当前直播间主播
                    tvCardFollow.setText("已关注");
                    tvCardFollow.setTextColor(getResources().getColor(R.color.mine_black_font));
                    //   tvCardFollow.setBackgroundResource(R.drawable.btn_recharge_gray);
                    tvFansCount.setText(String.valueOf(
                            Integer.parseInt(tvFansCount.getText().toString()) + 1
                    ));
                    userCard.hide();
                } else {
                    tvFollow.setVisibility(View.GONE);
                    userCard.hide();
                    sendFollowedMessage();
                }
            } else {
                Observerable.getInstance().notifyChange(ObserverableType.ATTENTION, -1);
                showToast("取消关注成功");
                if (userCard.isShowing()) {
                    tvCardFollow.setText("关注");
                    tvCardFollow.setTextColor(getResources().getColor(R.color.input_red));
                    //   tvCardFollow.setBackgroundResource(R.drawable.btn_recharge);
                    tvFansCount.setText(String.valueOf(
                            Integer.parseInt(tvFansCount.getText().toString()) - 1
                    ));
                }
            }
        } else {
            if (info.getIsSubscribe() == 1) {
                showToast("关注失败");
            } else {
                showToast("取消关注失败");
            }
        }
    }

    @Override
    public void showUserInfo(BaseData<UserInfo> anchorBaseData) {
        userCard.show();
        info = anchorBaseData.getObject();
        if (info == null) return;
        tvWords.setText(TextUtil.isEmpty(info.getPersonalsignature()) ? "这家伙很懒，啥都没说~"
                : info.getPersonalsignature());
        tvCardCharmCount.setText(String.valueOf(info.getCharmtotalvalue()));
        tvFansCount.setText(String.valueOf(info.getFans()));
        tvFollowCount.setText(String.valueOf(info.getSubscribenum()));
        tvCardId.setText("ID: " + String.valueOf(info.getId()));
        tvCardNickName.setText(info.getNickname());
        tvCardNickName.setCompoundDrawablesWithIntrinsicBounds(0, 0, info.getSex() == 0 ? R.drawable.icon_boy : R.drawable.icon_girl, 0);
        tvLevel.setText(String.valueOf(info.getLv()));
        Utils.setLevel(tvLevel, info.getLv());
        GlideUtil.load(this, info.getIcon(), imgCardHeader);
        if (info.getIsSubscribe() == 0) {
            tvCardFollow.setText("关注");
            tvCardFollow.setTextColor(getResources().getColor(R.color.input_red));
            //  tvCardFollow.setBackgroundResource(R.drawable.btn_recharge);
        } else {
            tvCardFollow.setText("已关注");
            tvCardFollow.setTextColor(getResources().getColor(R.color.mine_black_font));
            //    tvCardFollow.setBackgroundResource(R.drawable.btn_recharge_gray);
        }
        if (info.getId().equals(UserProxy.getUser().getUserId())) {
            spliteLine.setVisibility(View.GONE);
            tvCardFollow.setVisibility(View.GONE);
        } else {
            spliteLine.setVisibility(View.VISIBLE);
            tvCardFollow.setVisibility(View.VISIBLE);
        }
        if (mActivity instanceof LiveRoomActivity) {
            if (liveDetail != null && liveDetail.getInfo() != null
                    && info.getId().equals(liveDetail.getInfo().getUserId())
                    ) {
                tvReport.setVisibility(View.VISIBLE);
                tvReport.setText("举报");
            } else {
                tvReport.setVisibility(View.GONE);
            }
        } else {
            if (liveDetail != null && liveDetail.getInfo() != null
                    && info.getId().equals(liveDetail.getInfo().getUserId())
                    ) {
                tvReport.setVisibility(View.GONE);
            } else {
                tvReport.setVisibility(View.VISIBLE);
                tvReport.setText("禁言");
            }
        }
        tvCardFollow.setOnClickListener((view) -> {
            presenter.subscribeUp(info.getId());
        });
        tvHomePage.setOnClickListener((view) -> {
            Intent i = new Intent();
            i.setClass(mActivity, HomePageActivity.class);
            i.putExtra("otherId", info.getId());
            i.putExtra("isFromLive", true);
            jumpToActivity(i);
            userCard.hide();
        });
        tvReport.setOnClickListener((v) -> {
            if (mActivity instanceof LiveRoomActivity) {
                showReportDialog(info);
            } else {
                presenter.mute(UserProxy.getUser().getUserInfo().getLiveId(), info.getId());
            }
            userCard.hide();
        });
    }

    @Override
    public void getDailyResult(int num, BaseData result) {
        if (result.getCode() == 0) {
            try {
                JSONObject object = new JSONObject(result.getObject().toString());
                getDailyGold(object.getInt("count"));
                showDailyDialog(object.getInt("count"));
            } catch (JSONException e) {
                e.printStackTrace();
            }
            User user = UserProxy.getUser();
            UserInfo info = user.getUserInfo();
            info.setRainbowSweet(info.getRainbowSweet() + 30);
            UserProxy.setUser(user);
        } else {
            showSnackbar(getRootView(mActivity), result.getResult());
        }
    }

    @Override
    public void showInformResult(int code) {
        if (code == 0) {
            showSnackBar("谢谢您的举报，我们会尽快作出处理");
        }
    }

    @Override
    public void showMuteResult(BaseData baseData) {
        if (baseData.getCode() == 0) {
            showSnackBar("禁言成功");
        } else {
            showSnackBar(baseData.getResult());
        }
    }

    @Override
    public void setGameList(BaseData<List<GameInfo>> listBaseData) {
        this.gameList.clear();
        this.gameList.addAll(listBaseData.getObject());
        GameInfo gameInfo = new GameInfo();
        gameInfo.setId(-1);
        gameInfo.setName("更多游戏");
        this.gameList.add(gameInfo);
    }

    @Override
    public void showMissionList(BaseData<List<DayTaskData>> data) {
        if (data != null && data.getObject() != null) {
            missionDatas = data.getObject();
            showTaskDialog(missionDatas);
        }
    }

    @Override
    public void showMissionReward(BaseData<MissionData> data, DayTaskData dayTaskData) {
        if (data.getCode() == 0) {
            showSnackBar("任务奖励已领取");
            User user = UserProxy.getUser();
            UserInfo info = user.getUserInfo();
            info.setRainbowSweet(info.getRainbowSweet() + dayTaskData.getSweet());
            UserProxy.setUser(user);
            tvRainbowNum.setText(info.getRainbowSweet() + "");
            if (missionDatas != null && missionDatas.contains(dayTaskData)) {
                missionDatas.remove(dayTaskData);
            }
            adatpter.notifyDataSetChanged();
            if (data.getObject() != null) {
                isShowTask(data.getObject().getGetAllReward() == 0);
            }
        } else {
            showSnackBar(data.getResult());
        }

    }

    @Override
    public void showShareLivingResult(BaseData data) {
        if (data.getCode() == 0) {
        } else {
            showSnackBar(data.getResult());
        }
    }

    public void setLiveDetail(LiveDetailData liveDetail) {
        this.liveDetail = liveDetail;
        showDetail(liveDetail);
        if (liveDetail != null && liveDetail.getShare() != null) {
            initShareInfo(liveDetail.getShare());
            initShareInfo(liveDetail.getShare());
            sendEnterLiveRoomMsg2Server();
        }
    }

    /*设置直播间数据*/
    private void showDetail(LiveDetailData liveDetail) {
        if (liveDetail == null) return;
        if (liveDetail.getGameInfo() == null) {
            gameID = 0;
            ivHelp.setVisibility(View.GONE);
        } else {
            gameID = liveDetail.getGameInfo().getId();
            ivHelp.setVisibility(View.VISIBLE);
        }
        liveID = Integer.parseInt(liveDetail.getInfo().getLiveId());
        tvNickName.setText(liveDetail.getInfo().getNickname());
        tvRank.setText("魅力值：" + FormatUtil.formatDealTotal(liveDetail.getInfo().getCharmTotalValue()) + "");
        GlideUtil.load(this, liveDetail.getInfo().getUserIcon(), imgHeader);
        tvID.setText("ID " + liveDetail.getInfo().getUserId());
        giftView.setDatas(liveDetail.getGiftList());
        tvFollow.setVisibility(liveDetail.getInfo().getIsSubcribe() == 1 ? View.GONE : View.VISIBLE);
        initDailyShow();
        if (gameID == 0) {
            llChat.setTranslationY(DeviceUtils.dp2px(mActivity, 200));
        } else {
            llChat.setTranslationY(DeviceUtils.dp2px(mActivity, 0));
        }
        if (mActivity instanceof LiveRoomActivity && liveDetail.getInfo().getGetAllReward() == 0) {
            isShowTask(true);
        }
    }

    private void isShowTask(boolean isShow) {
        L.e(TAG, "isShow" + isShow);
        llTask.setVisibility(isShow ? View.VISIBLE : View.GONE);
    }

    /*发送送礼物请求到后台*/
    private void sendGiftMsgToServer(Gift gift) {
        if (user == null) {
            return;
        }
        RainbowMessage.CGSendGift.Builder builder = RainbowMessage.CGSendGift.newBuilder();
        builder.setUserId(Integer.parseInt(user.getUserId()));
        builder.setGiftId(gift.getId());
        builder.setNum(1);
        builder.setUpUserId(Integer.parseInt(liveDetail.getInfo().getUserId()));
        builder.setType(gift.getType());
        L.e(TAG, "sendGiftMsgToServer" + gift.getType());
        builder.setToken(UserProxy.getUser().getToken());
        Packet packet = Packet.newPbPacket(HOpCodeEx.CGSendGift, builder.build().toByteArray());
        packet.setFlag(9);
        packet.setStamp(System.currentTimeMillis());
        packet.setRetCode(0);
        MinaHelper.getInstance().sendMessageToServer(packet);
    }

    @Override
    public void onAnimationState(int state) {
        if (state == 1) {//结束
            if (!parentFragment.isShowGame() && llChat.getTranslationY() == 0) {
                parentFragment.showGameWithAnim();
            }
            if (llRewards.getVisibility() == View.INVISIBLE) {
                llRewards.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void showSnackBar(String tips) {
        showSnackbar(rlParent, tips);
    }

    @Override
    public void onUserChange(User user) {
        if (user != null) {
            this.user = user;
            giftView.setCoinsCount(user.getUserInfo().getRainbowSweet());
        }
    }

    public boolean isDialogShowing() {
        boolean isShowing = assictanceDialog != null && assictanceDialog.isShowing();
        if (isShowing) return isShowing;
        isShowing = inputDialog != null && inputDialog.isShowing();
        if (isShowing) return isShowing;
        isShowing = shareDialog != null && shareDialog.isShowing();
        if (isShowing) return isShowing;
        isShowing = reportDialog != null && reportDialog.isShowing();
        if (isShowing) return isShowing;
        isShowing = dailyDialog != null && dailyDialog.isShowing();
        if (isShowing) return isShowing;
        isShowing = introduceGameDialog != null && introduceGameDialog.isShowing();
        if (isShowing) return isShowing;
        isShowing = closeGameDialog != null && closeGameDialog.isShowing();
        return isShowing;
    }

    @Override
    public void getRainbow(DayTaskData data) {
        presenter.getMissonReward(data);
    }

    @Override
    public <T> void update(ObserverableType key, T data) {
        switch (key) {
            case SHARE:
                if (mActivity instanceof LiveRoomActivity && data instanceof Integer && (Integer) data == 1) {
                    presenter.shareLivingRequest(liveID);
                }
                break;
            case ISBANKER:
                isBanker = (Boolean) data;
                break;
            case EXITLIVEROOM:
                exitChatRoom();
                break;
            case GETBANKERINFO:
                presenter.getUserInfo((String) data);
                break;
        }

    }

    /**
     * 处理长连接交互
     */
    private static class ChatHandler extends Handler {
        WeakReference<FragmentChatRoom> weakReference;
        FragmentChatRoom fragment;

        public ChatHandler(FragmentChatRoom fragment) {
            this.weakReference = new WeakReference<FragmentChatRoom>(fragment);
            this.fragment = weakReference.get();
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CODE_SENDGIFT:

                    break;
                case CODE_DAILY:
                    long time = (long) msg.obj;
                    if (time > 1000) {
                        fragment.tvDailyTime.setText(FormatUtil.formatTime(time, "mm:ss"));
                        time -= 1000;
                        msg = obtainMessage();
                        msg.what = CODE_DAILY;
                        msg.obj = time;
                        sendMessageDelayed(msg, 1000);
                    } else {
                        fragment.tvDailyTime.setText("可领取");
                    }
                    break;
                case CODE_BIG_GIFT:
                    if (!weakReference.get().msgQueue.isEmpty()) {
                        int type = (int) msg.obj;
                        if (type == 2) {
                            weakReference.get().showBigGift(weakReference.get().msgQueue.poll());
                        } else {
                            weakReference.get().showBigGift(weakReference.get().msgQueue.peek());
                            weakReference.get().mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    weakReference.get().msgQueue.poll();
                                }
                            }, postDelayTime - 500);
                        }
                        Message msg2 = weakReference.get().mHandler.obtainMessage();
                        msg2.what = CODE_BIG_GIFT;
                        msg2.obj = 2;
                        weakReference.get().mHandler.sendMessageDelayed(msg2, postDelayTime);
                    } else {
                        weakReference.get().mHandler.removeMessages(CODE_BIG_GIFT);
                    }
                    break;
                case CODE_CLOSE_VIDEO:
                    weakReference.get().closeVideo();
                    break;
                case CODE_CLOSE_ALL:
                    weakReference.get().closeAll();
                    break;
                case CODE_CHANGE_GAME:
                    weakReference.get().changeGame((RainbowMessage.GCChangeGameRet) msg.obj);
                    break;
                case CODE_CLOSE_GAME:
                    weakReference.get().closeGame();
                    break;
            }
        }
    }

    private void closeGame() {
        if (mActivity instanceof PlayLiveRoomActivity) {
            if (!closeGame) {
                showSnackbar(getRootView(mActivity), "本局游戏结束后自动关闭游戏");
                Observerable.getInstance().notifyChange(ObserverableType.SWITCHGAME, 0);
                sendNotifyMessage("主播已关闭游戏，本局游戏结束后将自动关闭游戏");
                closeGame = true;
            }
        } else {
            L.e(TAG,"BBBBBBBBBB  33333333   deleteG");
            parentFragment.deleteGame();
        }
    }

    private void closeVideo() {
        if (mActivity instanceof LiveRoomActivity) {
            ((LiveRoomActivity) mActivity).hideVideoFragment();
        } else {
            ((PlayLiveRoomActivity) mActivity).stop();
            ((BaseActivity) mActivity).jumpToActivity(LiveEndActivity.class);
        }
    }

    private void closeAll() {
        mActivity.finish();
        Intent intent = new Intent(mActivity, LiveFinishActivity.class);
        if (mActivity instanceof LiveRoomActivity) {
            intent.putExtra("icon", liveDetail.getInfo().getUserIcon());
            intent.putExtra("conver", liveDetail.getInfo().getLiveIcon());
        } else {
            intent.putExtra("icon", user.getUserInfo().getIcon());
            intent.putExtra("conver", user.getUserInfo().getLiveIcon());
        }
        jumpToActivity(intent);
    }


    /*根据id查找礼物*/
    private Gift findGiftById(int id) {
        List<Gift> gifts = liveDetail.getGiftList();
        for (Gift gift : gifts) {
            if (gift.getId() == id) {
                return gift;
            }
        }
        return null;
    }

    /*离开直播间*/
    private void exitChatRoom() {
        if (mActivity instanceof LiveRoomActivity) {
            RainbowMessage.CGOutLiveRoom.Builder builder = RainbowMessage.CGOutLiveRoom.newBuilder();
            if (liveDetail != null) {
                builder.setLiveId(Integer.parseInt(liveDetail.getInfo().getLiveId()));
                builder.setUserId(Integer.parseInt(user.getUserId()));
            } else {
                return;
            }
            L.e("服务", " exit livedi " + builder.getLiveId() + "   userid  " + builder.getUserId());
            Packet packet = Packet.newPbPacket(HOpCodeEx.CGOutLiveRoom, builder.build().toByteArray());
            packet.setFlag(9);
            packet.setStamp(System.currentTimeMillis());
            packet.setRetCode(0);
            MinaHelper.getInstance().sendMessageToServer(packet);
        } else {
            RainbowMessage.CGOutLiveRoom.Builder builder = RainbowMessage.CGOutLiveRoom.newBuilder();
            builder.setLiveId(Integer.parseInt(user.getUserInfo().getLiveId()));
            builder.setUserId(Integer.parseInt(user.getUserId()));
            Packet packet = Packet.newPbPacket(HOpCodeEx.CGOutLiveRoom, builder.build().toByteArray());
            packet.setFlag(9);
            packet.setStamp(System.currentTimeMillis());
            packet.setRetCode(0);
            MinaHelper.getInstance().sendMessageToServer(packet);
        }
    }


    private void sortChatRoomMember(List<ChatRoomMember> members) {
        if (members == null) return;
        Collections.sort(members, new Comparator<ChatRoomMember>() {
            @Override
            public int compare(ChatRoomMember o1, ChatRoomMember o2) {
                if (o1.getExtension() == null || o2.getExtension() == null) return 0;
                if (!o1.getExtension().containsKey("level") || !o2.getExtension().containsKey("level"))
                    return 0;
                return ((Integer) o2.getExtension().get("level")).compareTo(
                        ((Integer) o1.getExtension().get("level"))
                );
            }
        });
    }

    /*通知服务器下线*/
    private void sendOfflineMsg2Server() {
        if (mActivity instanceof PlayLiveRoomActivity) {
            RainbowMessage.CGCloseLive.Builder builder = RainbowMessage.CGCloseLive.newBuilder();
            builder.setLiveId(Integer.parseInt(user.getUserInfo().getLiveId()));
            Packet packet = Packet.newPbPacket(HOpCodeEx.CGCloseLive, builder.build().toByteArray());
            packet.setFlag(9);
            packet.setStamp(System.currentTimeMillis());
            packet.setRetCode(0);
            MinaHelper.getInstance().sendMessageToServer(packet);
            L.e(TAG, "发送离线通知");
        }
    }

    /*通知服务器切换游戏*/
    private void sendChangeGameMsg2Server(int gameID) {

        L.e(TAG, "sendChangeGameMsg2Server id  " + gameID);
        RainbowMessage.CGChangeGame.Builder builder =
                RainbowMessage.CGChangeGame.newBuilder()
                        .setGameId(gameID)
                        .setUserId(Integer.parseInt(user.getUserId()))
//                .setToken(user.getToken())
                        .setLiveId(liveID);
        Packet packet = Packet.newPbPacket(HOpCodeEx.CGChangeGame, builder.build().toByteArray());
        packet.setFlag(9);
        packet.setStamp(System.currentTimeMillis());
        packet.setRetCode(0);
        MinaHelper.getInstance().sendMessageToServer(packet);
    }

    /*通知服务器关闭游戏*/
    private void sendCloseGameMsg2Server(int gameID) {
        RainbowMessage.CGNowCloseGame.Builder builder =
                RainbowMessage.CGNowCloseGame.newBuilder()
                        .setGameId(gameID)
                        .setUserId(Integer.parseInt(user.getUserId()))
                        .setToken(user.getToken())
                        .setLiveId(liveID);
        Packet packet = Packet.newPbPacket(HOpCodeEx.CGNowCloseGame, builder.build().toByteArray());
        packet.setFlag(9);
        packet.setStamp(System.currentTimeMillis());
        packet.setRetCode(0);
        MinaHelper.getInstance().sendMessageToServer(packet);
    }
}
